import time

from django.http import JsonResponse
from django.shortcuts import render
from django.views.generic import View

from BookType.models import BookType
from WebSite.commonUtil import LayuiTableData, ResponseJson


# Create your views here.
class IndexPage(View):
    def get(self, request):
        return render(request, 'bookTypeIndex.html')


class ListAllBookTypes(View):
    def get(self, request):
        bookTypes = BookType.objects.all()
        bookTypeList = []
        for bookType in bookTypes:
            itemJson = {
                'bookTypeId': bookType.book_type_id,
                'bookTypeName': bookType.book_type_name,
                'borrowDay': bookType.borrow_days,
                'createTime': bookType.create_time,
                'updateTime': bookType.update_time
            }
            bookTypeList.append(itemJson)
        resultData = LayuiTableData(0, "", len(bookTypeList), bookTypeList).getJsonData()
        return JsonResponse(resultData, safe=False)


class AddBookType(View):
    def post(self, request):
        resultData = ResponseJson("true", "操作成功", {}).getJsonData()
        try:
            bookType = BookType()
            bookType.book_type_name = request.POST.get("bookTypeName")
            bookType.borrow_days = request.POST.get("borrowDays")
            bookType.create_time = time.strftime('%Y-%m-%d %X', time.gmtime())
            bookType.update_time = time.strftime('%Y-%m-%d %X', time.gmtime())
            bookType.save()
        except Exception as err:
            print(err)
            resultData = ResponseJson("false", "操作失败", {}).getJsonData()

        return JsonResponse(resultData, safe=False)


class EditBookType(View):
    def post(self, request):
        resultData = ResponseJson("true", "操作成功", {}).getJsonData()
        try:
            bookType = BookType()
            bookType.book_type_id = request.POST.get("bookTypeId")
            bookType.book_type_name = request.POST.get("bookTypeName")
            bookType.borrow_days = request.POST.get("borrowDays")
            bookType.create_time = time.strftime('%Y-%m-%d %X', time.gmtime())
            bookType.update_time = time.strftime('%Y-%m-%d %X', time.gmtime())
            bookType.save()
        except Exception as err:
            print(err)
            resultData = ResponseJson("false", "操作失败", {}).getJsonData()

        return JsonResponse(resultData, safe=False)


class DeleteBookType(View):
    def post(self, request):
        resultData = ResponseJson("true", "操作成功", {}).getJsonData()
        try:
            bookType = BookType()
            bookType.book_type_id = request.POST.get("bookTypeId")
            bookType.delete()
        except Exception as err:
            print(err)
            resultData = ResponseJson("false", "操作失败", {}).getJsonData()

        return JsonResponse(resultData, safe=False)
